package com.qf.qfgateway.filter;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.R;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
@Order(-5)
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //资源放行
        String uri = request.getURI().toString();
        if (uri.contains("/login")){
            return chain.filter(exchange);
        }

        //判断是否登录 (获取token-参数&头+验证token)
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            token = request.getQueryParams().getFirst("token");
        }

        if (!StringUtils.isEmpty(token)){
            //校验-通过
            return chain.filter(exchange);
        }

        //为空 || 校验不通过 -- 提示登录
        response.getHeaders().set("content-type","application/json;charset=utf-8");

        R r = R.error().putData("尚未登录");
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(r).getBytes(StandardCharsets.UTF_8));
        Mono<DataBuffer> mono = Mono.just(dataBuffer);

        return response.writeWith(mono);

//        response.setStatusCode(HttpStatus.UNAUTHORIZED);
//        return response.setComplete();
    }
}
